package com.ym.controller.management;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import com.ym.core.config.ConfigCenterProperties;
import com.ym.core.domain.APIResponse;
import com.ym.core.domain.BaseController;
import com.ym.core.exception.BusinessException;
import com.ym.core.shiro.ShiroUtil;
import com.ym.core.utils.MultipartFileUtil;
import com.ym.core.utils.UnCompressFile;
import com.ym.core.utils.excel.ExportExcelUtil;
import com.ym.core.utils.excel.ImportExcelUtil;
import com.ym.core.utils.tkmybatis.TK;

import com.ym.medical.domain.entity.*;
import com.ym.medical.domain.param.DoctorNavInforParam;
import com.ym.medical.domain.param.NavDestHisParam;
import com.ym.medical.domain.param.NavDestYjParam;
import com.ym.medical.domain.vo.NavDestHisVo;

import com.ym.medical.enums.FileTypeEnum;
import com.ym.medical.enums.NavDeptTypeEnum;
import com.ym.medical.service.*;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * 导航数据管理
 */
@Api(tags = "导航数据管理")
@RestController
@RequestMapping("/management/navigate")
public class NavigateManagement extends BaseController {

	private static final Logger LOGGER = LoggerFactory.getLogger(NavigateManagement.class);
	@Autowired
	protected ConfigCenterProperties configCenterProperties;

	@Autowired
	private INavDestYjSV navDestYjSV;
	@Autowired
	private INavDestHisSV navDestHisSV;
	@Autowired
	private IDoctorNavInforSV doctorNavInforSV;
	@Autowired
	private ISysDictSV sysDictSV;
	@Autowired
	private IHospitalCodeMapSV hospitalCodeMapSV;
	@Autowired
	private IFileInforSV fileInforSV;
	@Autowired
	protected RestTemplate restTemplate;

	@ApiOperation("导入云景科室/诊室数据")
	@PostMapping("/yjData/import")
	public APIResponse importYJNavigateData(@ApiParam(name = "file", value = "文件", required = true) MultipartFile file,
											@ApiParam(name = "hosName", value = "医院名称", required = true) String hosName,
											@ApiParam(name = "hosCode", value = "医院编码", required = true) String hosCode) throws IOException {
		/*获取当前用户id*/
		Long userId = ShiroUtil.getLoginId();;

		/**获取文件*/
		String fileName = file.getOriginalFilename();

		/**将MultipartFile转为File*/
		String yjDeptJson = configCenterProperties.getTmpFileConfig().getPathMap().get("yjDeptJson");
		String idsUUID = UUID.randomUUID().toString().replace("-","");
		//目标上传目录
		String destPath = yjDeptJson + File.separator + idsUUID;
		MultipartFileUtil.copyFile(file, destPath);

		/**将文件转成json文件*/
		String input = FileUtils.readFileToString(new File(destPath + File.separator + fileName), "UTF-8");
		JSONObject jsonObject = new JSONObject(input);
		List<NavDestYjEntity> navDestYjs = new ArrayList<>();
		NavDestYjEntity navDestYj;
		if (jsonObject != null) {
			/**获取json下的order数组*/
			JSONArray orderArray = jsonObject.getJSONArray("order");
			JSONArray jsonArray;
			/**遍历order数组*/
			for (Object key : orderArray) {
				if (!"icon".equals(key)) {
					/*获取楼群名称*/
					String build = String.valueOf(key);
					jsonArray = jsonObject.getJSONArray(build);
					/**遍历每个key对应的数组*/
					for (Object building : jsonArray) {
						JSONObject buildingJson = new JSONObject(building);
						/*楼群编码*/
						String bd_id = String.valueOf(buildingJson.get("bd_id"));
						/*科室名称*/
						String deptName = String.valueOf(buildingJson.get("name"));
						/*科室编码*/
						String deptCode = String.valueOf(buildingJson.get("dpt_id"));
						/*楼层编码*/
						String flId = String.valueOf(buildingJson.get("fl_id"));

						/**新增一个科室对象*/
						navDestYj = genarateYjBuild(userId, hosCode, hosName, build, bd_id, deptName, deptCode, flId, NavDeptTypeEnum.DEPARTMENT.getKey());
						navDestYjs.add(navDestYj);
					}
				}
			}
			/*net.sf.json.JSONArray iconArray = jsonObject.getJSONArray("icon");
			 *//**遍历order数组*//*
			for (Object iconObject : iconArray) {
				JSONObject iconJson = JSONObject.fromObject(iconObject);
				String build =  iconJson.getString("name");
				JSONArray poiArray = iconJson.getJSONArray("poi");
				*//**遍历每个key对应的数组*//*
				for (Object building : poiArray) {
					JSONObject buildingJson = JSONObject.fromObject(building);
					*//*楼群编码*//*
					String bd_id = String.valueOf(buildingJson.get("bd_id"));
					*//*诊室名称*//*
					String deptName = String.valueOf(buildingJson.get("name"));
					*//*诊室编码*//*
					String deptCode = String.valueOf(buildingJson.get("dpt_id"));
					*//*楼层编码*//*
					String flId = String.valueOf(buildingJson.get("fl_id"));

					*//**新增一个科室对象*//*
					navDestYj = genarateYjBuild(userId, hosCode, hosName, build, bd_id, deptName, deptCode, flId,NavDeptTypeEnum.CLINIC.getKey());
					navDestYjs.add(navDestYj);
				}
			}*/
		}
		navDestYjSV.insertBatch(navDestYjs);
		return successMsg("导入导航数据成功");
	}

	@ApiOperation("修改云景科室/诊室数据")
	@PostMapping("/yjData/update")
	public APIResponse updateYJNavigateData(@ApiParam(name = "navDestYj", value = "导航数据（云景）实体", required = true)
											@RequestBody @Validated(value = {NavDestYjEntity.Update.class}) NavDestYjEntity navDestYj) {
		Long userId = ShiroUtil.getLoginId();;
		navDestYj.setModifier(userId);
		int flag = navDestYjSV.updateById(navDestYj);
		if (flag <= 0 ) {
			return failMsg("修改导航数据失败");
		}
		return successMsg("修改导航数据成功");
	}

	@ApiOperation("删除云景科室/诊室数据")
	@PostMapping("/yjData/delete")
	public APIResponse deleteYJNavigateData(@ApiParam(name = "ids", value = "导航数据（云景）实体id", required = true)
											@RequestBody Long[] ids) {
		if (ids.length <= 0) {
			throw new BusinessException("请至少选择一个");
		}

		int flag = navDestYjSV.deleteByIds(ids);
		if (flag == 0) {
			return failMsg("删除导航数据失败");
		}
		return successMsg("删除导航数据成功");
	}

	@ApiOperation("云景科室/诊室数据 展示/搜索")
	@GetMapping("/yjData/list")
	public APIResponse<PageInfo<NavDestYjEntity>> listYJNavigateData(@ApiParam(name = "navDestYj", value = "导航数据（云景）实体", required = true)
																			 NavDestYjParam navDestYjModel,
                                                               @RequestParam(required = false, defaultValue = "1") int pageNo,
                                                               @RequestParam(required = false) int limit) {
		/*String sql = "where 1=1 ";
		String bdgName = navDestYjModel.getBdgName();
		String bdgId = navDestYjModel.getBdgId();
		String deptName = navDestYjModel.getDeptName();
		String deptCode = navDestYjModel.getDeptCode();
		String deptType = navDestYjModel.getDeptType();

		String hosCode = navDestYjModel.getHosCode();
		if (!StringUtils.isBlank(hosCode)) {
			HospitalCodeMapModel model = new HospitalCodeMapModel();
			model.setYmHospitalCode(hosCode);
			List<HospitalCodeMap> hospitalCodeMaps = hospitalCodeMapSV.selectByModel(model);
			if (hospitalCodeMaps == null || hospitalCodeMaps.isEmpty()) {
				return APIResponseBuilder.successWithMsg("导航数据（云景）展示/搜索成功", new PageInfo<NavDestYj>());
			} else {
				sql += "and bdg_id = '" + hospitalCodeMaps.get(0).getPartnerHospitalCode() + "' ";
			}
		}
		if (!StringUtils.isBlank(bdgName)) {
			sql += "and bdg_name like CONCAT('%','" + bdgName + "','%') ";
		}
		if (!StringUtils.isBlank(bdgId)) {
			sql += "and bdg_id like CONCAT('" + bdgId + "','%') ";
		}
		if (!StringUtils.isBlank(deptName)) {
			sql += "and dept_name like CONCAT('%','" + deptName + "','%') ";
		}
		if (!StringUtils.isBlank(deptCode)) {
			sql += "and dept_code like CONCAT('" + deptCode + "','%') ";
		}
		if (!StringUtils.isBlank(deptType)) {
			sql += "and dept_type = '" + deptType + "' ";
		}
		navDestYjModel.setQueryByWhereClause(sql);
		navDestYjModel.setOrderByClause("create_time desc");
		if(limit <= 0){
			limit = navDestYjSV.countByModel(navDestYjModel);
		}*/
		PageHelper.startPage(pageNo,limit);
		List<NavDestYjEntity> navDestYjPageInfo = navDestYjSV
				.selectList(navDestYjModel.covert());
		return successPage(navDestYjPageInfo);
	}

	@ApiOperation("云景科室数据导出")
	@GetMapping("/exportYjData")
	public void exportYjData(@ApiParam(name = "navDestYj", value = "导航数据（云景）实体", required = true)
									 NavDestYjParam navDestYjModel,
							 @RequestParam(required = false, defaultValue = "1") int pageNo,
							 @RequestParam(required = false) int limit,
							 HttpServletResponse response) throws Exception {
		ExportExcelUtil exportExcelUtil = new ExportExcelUtil();
		String titleName = "云景科室数据管理";
		String[] headerString = {"序号", "医院名称", "医院编码", "楼群名称", "楼群编码", "科室名称", "科室编码", "科室类别", "楼层编码"};
		String[] headerField = {"id", "bdgName", "bdgId", "bdName", "bdId", "deptName", "deptCode", "deptType", "flId"};
		List<NavDestYjEntity> list = navDestYjSV
				.selectList(navDestYjModel.covert());
		exportExcelUtil.exportExcelForTotal(titleName, headerString, headerField, null, list, response, null);
	}

	@ApiOperation("新增云景科室/诊室数据")
	@PostMapping("/yjData/add")
	public APIResponse insertYJNavigateData(@ApiParam(name = "navDestYj", value = "导航数据（云景）实体", required = true)
															@RequestBody @Validated(value = {NavDestYjParam.Add.class}) NavDestYjParam navDestYjModel) {
		Long userId = ShiroUtil.getLoginId();;
		navDestYjModel.setCreator(userId);
		long flag = navDestYjSV.insert(navDestYjModel.covert());
		if (flag <= 0) {
			return successMsg("导航数据（云景）新增失败");
		}
		return APIResponse.success("导航数据（云景）新增成功", navDestYjModel.covert());
	}

	/**
	 * 新增一条云景导航数据
	 *
	 * @param userId
	 * @param hosCode
	 * @param hosName
	 * @param build
	 * @param bd_id
	 * @param deptName
	 * @param deptCode
	 * @param flId
	 * @return
	 */
	private NavDestYjEntity genarateYjBuild(Long userId, String hosCode, String hosName, String build, String bd_id, String deptName, String deptCode, String flId, String deptType) {
		NavDestYjEntity navDestYj = new NavDestYjEntity();
		/*医院名称*/
		navDestYj.setBdgName(hosName);
		/*医院编码*/
		navDestYj.setBdgId(hosCode);
		/*楼群名称*/
		navDestYj.setBdName(build);
		/*楼群编码*/
		navDestYj.setBdId(bd_id);
		/*科室名称*/
		navDestYj.setDeptName(deptName);
		/*科室编码*/
		navDestYj.setDeptCode(deptCode);
		/*楼层编码*/
		navDestYj.setFlId(flId);
		/*创建人*/
		navDestYj.setCreator(userId);
		/*创建时间*/
		navDestYj.setDeptType(deptType);
		navDestYj.setCreateTime(new Date());
		return navDestYj;
	}

	@ApiOperation("新增HIS科室/诊室数据")
	@PostMapping("/hisData/add")
	public APIResponse<NavDestHisEntity> insertHISNavigateData(@ApiParam(name = "navDestHis", value = "导航数据（HIS）实体", required = true)
														 @RequestBody @Validated(value = {NavDestHisParam.Add.class}) NavDestHisParam navDestHisModel) {
		NavDestHisEntity navDestHis = navDestHisModelCopyToRecord(navDestHisModel);
		Long userId = ShiroUtil.getLoginId();;
		navDestHis.setCreator(userId);
		long flag = navDestHisSV.insert(navDestHis);
		if (flag <=0) {
			return successMsg("导航数据（HIS）新增失败");
		}
		return APIResponse.success("导航数据（HIS）新增成功", navDestHis);
	}

	@ApiOperation("修改HIS科室/诊室数据")
	@PostMapping("/hisData/update")
	public APIResponse<NavDestHisEntity> updateHISNavigateData(@ApiParam(name = "navDestHis", value = "导航数据（HIS）实体", required = true)
														 @RequestBody @Validated(value = {NavDestHisParam.Update.class}) NavDestHisParam navDestHisModel) {
		NavDestHisEntity navDestHis = navDestHisModelCopyToRecord(navDestHisModel);
		Long userId = ShiroUtil
				.getLoginId();
		navDestHis.setModifier(userId);
		int flag = navDestHisSV.updateById(navDestHis);
		if (flag <= 0) {
			return successMsg("导航数据（HIS）新增失败");
		}
		return APIResponse.success("导航数据（HIS）新增成功", navDestHis);
	}


	/**
	 * @param navDestHisModel
	 * @return
	 */
	private NavDestHisEntity navDestHisModelCopyToRecord(NavDestHisParam navDestHisModel) {
		String hosCode = navDestHisModel.getYjHosCode();
		String deptCode = navDestHisModel.getYjDeptCode();
		String hosDeptCode = navDestHisModel.getYjHosDeptCode();
		if (StringUtils.isNotEmpty(hosDeptCode)) {
			if (hosDeptCode.contains("_")) {
				String[] hosDeptCodeArr = hosDeptCode.split("_");
				hosCode = hosDeptCodeArr[0];
				deptCode = hosDeptCodeArr[1];
			}
		}
		navDestHisModel.setYjHosCode(hosCode);
		navDestHisModel.setYjDeptCode(deptCode);
		NavDestHisEntity navDestHis = new NavDestHisEntity();
		BeanUtils.copyProperties(navDestHisModel, navDestHis);
		return navDestHis;
	}

	@ApiOperation("删除HIS科室/诊室数据")
	@PostMapping("/hisData/delete")
	public APIResponse deleteHISNavigateData(@ApiParam(name = "ids", value = "导航数据（HIS）实体id", required = true)
											 @RequestBody Long[] ids) {
		if (ids.length <= 0) {
			throw new BusinessException("请至少选择一个");
		}
		int flag = navDestHisSV.deleteByIds(ids);
		if (flag == 0) {
			return failMsg("导航数据（HIS）删除失败");
		}
		return successMsg("导航数据（HIS）删除成功");
	}

	@ApiOperation("HIS科室/诊室数据 展示/搜索")
	@GetMapping("/hisData/list")
	public APIResponse<PageInfo<NavDestHisVo>> listHISNavigateData(@ApiParam(name = "navDestHis", value = "导航数据（HIS）实体", required = true)
																			  NavDestHisParam navDestHisModel,
																   @RequestParam(required = false, defaultValue = "1") int pageNo,
																   @RequestParam(required = false) int limit) {
		/*String hosCode = navDestHisModel.getHosCode();
		String deptCode = navDestHisModel.getDeptCode();
		String hosName = navDestHisModel.getHosName();
		String deptName = navDestHisModel.getDeptName();
		String deptType = navDestHisModel.getDeptType();
		String roomName = navDestHisModel.getRoomName();
		String roomCode = navDestHisModel.getRoomCode();
		String sql = "where 1=1 ";
		if (!StringUtils.isBlank(hosName)) {
			sql += "and hos_name like CONCAT('%','" + hosName + "','%') ";
		}
		if (!StringUtils.isBlank(hosCode)) {
			sql += "and hos_code like CONCAT('" + hosCode + "','%') ";
		}
		if (!StringUtils.isBlank(deptName)) {
			sql += "and dept_name like CONCAT('%','" + deptName + "','%') ";
		}
		if (!StringUtils.isBlank(deptCode)) {
			sql += "and dept_code like CONCAT('" + deptCode + "','%') ";
		}
		if (!StringUtils.isBlank(deptType)) {
			sql += "and dept_type = '" + deptType + "' ";
		}
		if (!StringUtils.isBlank(roomName)) {
			sql += "and room_name like CONCAT('%','" + roomName + "','%') ";
		}
		if (!StringUtils.isBlank(roomCode)) {
			sql += "and room_code like CONCAT('" + roomCode + "','%') ";
		}
		navDestHisModel.setQueryByWhereClause(sql);
		navDestHisModel.setOrderByClause("create_time desc");
		if(limit <= 0){
			limit = navDestHisSV.countByModel(navDestHisModel);
		}*/
		PageInfo<NavDestHisVo> navDestHisPageInfo = navDestHisSV.listHISNavigateData(navDestHisModel, pageNo, limit);
		return APIResponse.success("导航数据（HIS）展示/搜索", navDestHisPageInfo);
	}

	@ApiOperation("HIS科室数据导出")
	@GetMapping("/exportHisData")
	public void exportHisData(@ApiParam(name = "navDestHis", value = "导航数据（HIS）实体", required = true)
									  NavDestHisParam navDestHisModel,
							  @RequestParam(required = false, defaultValue = "1") int pageNo,
							  @RequestParam(required = false) int limit,
							  HttpServletResponse response) throws Exception {
		ExportExcelUtil exportExcelUtil = new ExportExcelUtil();
		String titleName = "HIS科室数据管理";
		String[] headerString = {"序号", "医院名称", "医院编码", "科室名称", "科室编码", "科室类别", "关联标识", "诊室名称", "诊室编码"};
		String[] headerField = {"id", "hosName", "hosCode", "deptName", "deptCode", "deptType", "yjHosDeptCode", "roomName", "roomCode"};
		PageInfo<NavDestHisVo> navDestHisPageInfo = navDestHisSV.listHISNavigateData(navDestHisModel, pageNo, limit);
		exportExcelUtil.exportExcelForTotal(titleName, headerString, headerField, null, navDestHisPageInfo.getList(), response, null);
	}

	@ApiOperation("根据HIS医院code和云景医院科室查询对应的云景信息")
	@GetMapping("/yjData/hisHosCode")
	public APIResponse<PageInfo<NavDestYjEntity>> selectYjDataByHisHosCode(@ApiParam(name = "hosCode", value = "导航数据（HIS）医院编码", required = true)
																	 @RequestParam String hosCode,
                                                                     @ApiParam(name = "deptName", value = "导航数据（云景）科室名称", required = true)
																	 @RequestParam String deptName,
                                                                     @ApiParam(name = "deptType", value = "HIS科室类别", required = true)
																	 @RequestParam String deptType,
                                                                     @RequestParam(required = false, defaultValue = "1") int pageNo,
                                                                     @RequestParam(required = false, defaultValue = "10") int limit) {
		PageInfo<NavDestYjEntity> navDestYjPageInfo = navDestHisSV.selectYjDataByHisHosCode(hosCode, deptName, deptType, pageNo, limit);
		return APIResponse.success("导航数据（HIS）展示/搜索", navDestYjPageInfo);
	}


	@ApiOperation("查询HIS医生列表信息")
	@GetMapping("/his/getHisDoctorPage")
	public APIResponse<PageInfo<DoctorNavInforEntity>> getHisDoctorPage(@ApiParam(name = "navDestHis", value = "导航数据（HIS）实体", required = true)
																				DoctorNavInforParam model,
																		@RequestParam(required = false, defaultValue = "1") int pageNo,
																		@RequestParam(required = false) int limit) {
		/*String hosName = model.getHosName();
		String hosCode = model.getHosCode();
		String deptName = model.getDeptName();
		String deptCode = model.getDeptCode();
		String doctorName = model.getDoctorName();
		String doctorStaffNo = model.getDoctorStaffNo();
		String sql = "where 1=1 ";
		if (!StringUtils.isBlank(hosName)) {
			sql += "and hos_name like CONCAT('%','" + hosName + "','%') ";
		}
		if (!StringUtils.isBlank(hosCode)) {
			sql += "and hos_code like CONCAT('" + hosCode + "','%') ";
		}
		if (!StringUtils.isBlank(deptName)) {
			sql += "and dept_name like CONCAT('" + deptName + "','%') ";
		}
		if (!StringUtils.isBlank(deptCode)) {
			sql += "and dept_code like CONCAT('" + deptCode + "','%') ";
		}
		if (!StringUtils.isBlank(doctorName)) {
			sql += "and doctor_name like CONCAT('%','" + doctorName + "','%') ";
		}
		if (!StringUtils.isBlank(doctorStaffNo)) {
			sql += "and doctor_staff_no like CONCAT('" + doctorStaffNo + "','%') ";
		}
		model.setQueryByWhereClause(sql);
		if(limit <= 0){
			limit = doctorNavInforSV.countByModel(model);
		}*/
		PageHelper.startPage(pageNo,limit);
		List<DoctorNavInforEntity> pageInfo = doctorNavInforSV
				.selectList(model.covert());
		return successPage(pageInfo);
	}

	@ApiOperation("HIS医生数据导出")
	@GetMapping("/exportHisDoctorData")
	public void exportHisDoctorData(@ApiParam(name = "navDestHis", value = "导航数据（HIS）实体", required = true)
											DoctorNavInforParam model,
									@RequestParam(required = false, defaultValue = "1") int pageNo,
									@RequestParam(required = false) int limit,
									HttpServletResponse response) throws Exception {
		ExportExcelUtil exportExcelUtil = new ExportExcelUtil();
		String titleName = "HIS医生数据管理";
		String[] headerString = {"医生名称", "医生工号", "医院名称", "医院编码", "科室名称", "科室编码", "职称", "职位", "学历"};
		String[] headerField = {"doctorName", "doctorStaffNo", "hosName", "hosCode", "deptName", "deptCode", "titleName", "job", "eduName"};
		PageHelper.startPage(pageNo,limit);
		List<DoctorNavInforEntity> list = doctorNavInforSV
				.selectList(model.covert());
		exportExcelUtil.exportExcelForTotal(titleName, headerString, headerField, null, list, response, null);
	}


	@ApiOperation("同步医院科室信息")
	@PostMapping(value = "syncAllDeptInfo")
	public APIResponse syncAllDeptInfo(@RequestParam String hosCode) {
		Long userId = ShiroUtil.getLoginId();;
		return restTemplate.postForObject(configCenterProperties.getNavDataServerConfig().getBasePath() + "ymData/syncAllDeptInfo?hosCode=" + hosCode + "&userId=" + userId, null, APIResponse.class);
	}

	@ApiOperation("同步医院医生信息")
	@PostMapping(value = "syncAllDoctorInfo")
	public APIResponse syncAllDoctorInfo(@RequestParam String hosCode) {
		Long userId = ShiroUtil.getLoginId();;
		return restTemplate.postForObject(configCenterProperties.getNavDataServerConfig().getBasePath() + "ymData/syncAllDoctorInfo?hosCode=" + hosCode + "&userId=" + userId, null, APIResponse.class);
	}

	@ApiOperation("导入HIS科室/诊室数据")
	@PostMapping("/uploadHISDept")
	@ResponseBody
	public APIResponse<Map<String, Object>> uploadHISDept(
			@ApiParam(name = "excelFile", value = "HIS科室信息", required = true) MultipartFile excelFile,
			@ApiParam(name = "hosName", value = "医院名称", required = true) String hosName,
			@ApiParam(name = "hosCode", value = "医院编码", required = true) String hosCode
	) {
		if (excelFile == null || excelFile.isEmpty()) {
			return failMsg("文件不存在");
		}
		Long userId = ShiroUtil.getLoginId();;
		InputStream inputStream = null;
		Map<String, Object> map = new HashMap<>();
		int startLine = 2;
		try {
			String fileName = excelFile.getOriginalFilename();
			inputStream = excelFile.getInputStream();
			List<NavDestHisEntity> navDestHisList =
					ImportExcelUtil.readExcel
							(inputStream, fileName, startLine, NavDestHisEntity.class, ImportExcelUtil.getHISDeptTemplate());


			LOGGER.info("---------------------------------- HIS科室导入中 {}---------------------------------------------", navDestHisList);
			Map<String, String> NavDestHisOutpOrInpEnum = sysDictSV.getDictValuesToMap("NavDestHisOutpOrInpEnum");
			Map<String, String> NavDestHisClinicAttrEnum = sysDictSV.getDictValuesToMap("NavDestHisClinicAttrEnum");
			Map<String, String> NavDeptTypeEnum = sysDictSV.getDictValuesToMap("NavDeptTypeEnum");
			if (navDestHisList != null && !navDestHisList.isEmpty()) {
				for (NavDestHisEntity navDestHis : navDestHisList) {
					navDestHis.setHosName(hosName);
					navDestHis.setHosCode(hosCode);
					navDestHis.setOutpOrInp(NavDestHisOutpOrInpEnum.get(navDestHis.getOutpOrInp()));
					navDestHis.setClinicAttr(NavDestHisClinicAttrEnum.get(navDestHis.getClinicAttr()));
					navDestHis.setDeptType(NavDeptTypeEnum.get(navDestHis.getDeptType()));
				}
			} else {
				return successMsg("Excel无数据，已导入0条记录！");
			}
			map = navDestHisSV.uploadHisDeptInfo(navDestHisList, userId);
		} catch (Exception e) {
			LOGGER.error("异常:", e);
			return failMsg(e.getMessage());
		} finally {
			try {
				inputStream.close();
			} catch (IOException e) {
				LOGGER.error("IO异常:", e);
				return failMsg("IO异常");
			}
		}

		return successData(map);
	}

	@ApiOperation("导入HIS医生数据")
	@PostMapping("/uploadHISDoctor")
	@ResponseBody
	public APIResponse<Map<String, Object>> uploadHISDoctor(
			@ApiParam(name = "excelFile", value = "HIS科室信息", required = true) MultipartFile excelFile,
			@ApiParam(name = "hosName", value = "医院名称", required = true) String hosName,
			@ApiParam(name = "hosCode", value = "医院编码", required = true) String hosCode) {
		if (excelFile == null || excelFile.isEmpty()) {
			return failMsg("文件不存在");
		}
		Long userId = ShiroUtil.getLoginId();
		InputStream inputStream = null;
		Map<String, Object> map = new HashMap<>();
		int startLine = 2;
		try {
			String fileName = excelFile.getOriginalFilename();
			inputStream = excelFile.getInputStream();
			List<DoctorNavInforEntity> doctorNavInfors =
					ImportExcelUtil.readExcel
							(inputStream, fileName, startLine, DoctorNavInforEntity.class, ImportExcelUtil.getHISDoctorTemplate());
			inputStream.close();
			LOGGER.info("---------------------------------- HIS医生导入中 {}---------------------------------------------", doctorNavInfors);
			Map<String, String> DoctorJobTitle = sysDictSV.getDictValuesToMap("DoctorJobTitle");
			Map<String, String> DoctorNavInforEduEnum = sysDictSV.getDictValuesToMap("DoctorNavInforEduEnum");
			if (doctorNavInfors != null && !doctorNavInfors.isEmpty()) {
				for (DoctorNavInforEntity doctorNavInfor : doctorNavInfors) {
					doctorNavInfor.setHosName(hosName);
					doctorNavInfor.setHosCode(hosCode);
					doctorNavInfor.setTitle(DoctorJobTitle.get(doctorNavInfor.getTitle()));
					doctorNavInfor.setEdu(DoctorNavInforEduEnum.get(doctorNavInfor.getEdu()));
				}
			} else {
				return successMsg("Excel无数据，已导入0条记录！");
			}
			map = doctorNavInforSV.uploadHisDeptInfo(doctorNavInfors, userId);
		} catch (Exception e) {
			return failMsg(e.getMessage());
		}

		return successData(map);
	}

	@ApiOperation("导入HIS医生照片数据")
	@PostMapping("/uploadHISDoctorPhoto")
	@ResponseBody
	public APIResponse<Map<String, Object>> uploadHISDoctorPhoto(
			@ApiParam(name = "rarFile", value = "HIS医生图片压缩文件", required = true) MultipartFile rarFile,
			@ApiParam(name = "hosName", value = "医院名称", required = true) String hosName,
			@ApiParam(name = "hosCode", value = "医院编码", required = true) String hosCode) {
		if (rarFile == null || rarFile.isEmpty()) {
			return failMsg("文件不存在");
		}
		try {
			String hisDoctorPhoto = configCenterProperties.getTmpFileConfig().getPathMap().get("hisDoctorPhoto");
			String idsUUID = UUID.randomUUID().toString().replace("-","");
			//目标上传目录
			String destPath = hisDoctorPhoto + File.separator + idsUUID;
			File targetDir = new File(destPath);

			String zipFileName = rarFile.getOriginalFilename();
			File targetFile = new File(destPath, zipFileName);
			if (!targetDir.exists()) {
				targetDir.mkdirs();
			}
			rarFile.transferTo(targetFile);
			UnCompressFile.getInstance().deCompress(destPath + File.separator + zipFileName, destPath);
			File photoDir = new File(destPath + File.separator + zipFileName.substring(0, zipFileName.lastIndexOf(".")));
			File[] photoFiles = photoDir.listFiles();
			if (photoFiles != null && photoFiles.length > 0) {
				SysUserEntity currentUser = ShiroUtil.getLoginUser(SysUserEntity.class);
				Long currentUserId = currentUser == null ? null : currentUser.getId();
				FileInforEntity fileInfor;
				List<DoctorNavInforEntity> doctorNavInfors;
				List<DoctorNavInforEntity> doctorNavInforsSuc = new ArrayList<>();
				DoctorNavInforEntity doctorNavInfor;
				int i = 1;
				for (File photoFile : photoFiles) {
					String fileName = photoFile.getName().substring(0, photoFile.getName().lastIndexOf("."));
					doctorNavInfors = doctorNavInforSV.selectList(
							DoctorNavInforEntity.builder().hosCode(hosCode)
									.doctorStaffNo(fileName).build()
					);
					if (doctorNavInfors != null && !doctorNavInfors.isEmpty()) {
						String id = fileInforSV.uploadFile(photoFile, FileTypeEnum.IMG, "doctor_nav_infor", "photo", "HIS医生图像", currentUserId);
//						fileInfor.setId((i++)+"");
						doctorNavInfor = doctorNavInfors.get(0);
						doctorNavInfor.setPhoto(configCenterProperties.getQiNiuYunConfig().getShowImageUrl() + id);
						doctorNavInforsSuc.add(doctorNavInfor);
					}
				}
				doctorNavInforSV.batchUpdatePhoto(doctorNavInforsSuc);
			}
		} catch (Exception e) {
			LOGGER.error("异常:", e);
			return failMsg(e.getMessage());
		}
		return APIResponse.success();
	}

	@ApiOperation("新增HIS医生数据")
	@PostMapping("/hisDoctor/add")
	public APIResponse<DoctorNavInforEntity> insertHISDoctorNavInfor(
			@ApiParam(name = "doctorNavInfor", value = "导航数据（HIS医生）实体", required = true)
			@RequestBody @Validated(value = {DoctorNavInforParam.Add.class}) DoctorNavInforParam doctorNavInfor) {
		Long userId = ShiroUtil.getLoginId();
		doctorNavInfor.setCreator(userId);
		DoctorNavInforEntity doctorinfo = getDoctorNavInfor(doctorNavInfor.covert());
		long flag = doctorNavInforSV.insert(doctorinfo);
		if (flag <= 0) {
			return successMsg("导航数据（HIS医生）新增失败");
		}
		return APIResponse.success("导航数据（HIS医生）新增成功", doctorinfo);
	}

	private DoctorNavInforEntity getDoctorNavInfor(DoctorNavInforEntity doctorNavInfor) {
		if (StrUtil.isEmpty(doctorNavInfor.getHosCode())) {
			throw new BusinessException("请传入医院编码");

		}
		if (StringUtils.isBlank(doctorNavInfor.getDeptCode())) {
			throw new BusinessException("请传入科室编码");

		}
		//根据医院编码科室编码查询信息
		List<NavDestHisEntity> navDestHis = navDestHisSV
				.selectList(NavDestHisEntity.builder()
				.hosCode(doctorNavInfor.getHosCode()).deptCode(doctorNavInfor.getDeptCode())
				.build());
		if (!navDestHis.isEmpty()) {
			NavDestHisEntity navHis = navDestHis.get(0);
			doctorNavInfor.setHosName(navHis.getHosName());
			doctorNavInfor.setDeptName(navHis.getDeptName());
		}
		return doctorNavInfor;
	}

	@ApiOperation("修改HIS医生数据")
	@PostMapping("/hisDoctor/update")
	public APIResponse<DoctorNavInforEntity> updateHISDoctorNavInfor(
			@ApiParam(name = "doctorNavInfor", value = "导航数据（HIS医生）实体", required = true)
			@RequestBody @Validated(value = {DoctorNavInforParam.Update.class}) DoctorNavInforParam doctorNavInfor) {
		Long userId = ShiroUtil.getLoginId();
		doctorNavInfor.setModifier(userId);
		DoctorNavInforEntity doctorInfor = getDoctorNavInfor(doctorNavInfor.covert());
		int flag = doctorNavInforSV.updateById(doctorInfor);
		if (flag <=0) {
			return successMsg("导航数据（HIS医生）修改失败");
		}
		return APIResponse.success("导航数据（HIS医生）修改成功", doctorInfor);
	}

	@ApiOperation("删除HIS医生数据")
	@PostMapping("/hisDoctor/delete")
	public APIResponse deleteHISDoctorNavInfor(@ApiParam(name = "ids", value = "导航数据（云景）实体id", required = true)
											   @RequestBody Long[] ids) {
		if (ids.length <= 0) {
			throw new BusinessException("请至少选择一个");
		}
		doctorNavInforSV.deleteByIds(ids);
		return APIResponse.success("导航数据（HIS医生）删除成功", ids);
	}

	@ApiOperation("查询HIS医院编码/医院名称")
	@GetMapping("/getHisHospital")
	public APIResponse<PageInfo<NavDestHisEntity>> getHisHospital(
			@RequestParam(required = false, defaultValue = "1") int pageNo,
			@RequestParam(required = false, defaultValue = "10") int limit
	) {
		PageHelper.startPage(pageNo,limit);
		List<NavDestHisEntity> pageInfo = navDestHisSV.selectList(
				TK.select(NavDestHisEntity.class)
				.column("id","hos_code","hos_name").where().end()
		);
		return successPage(pageInfo);
	}

	@ApiOperation("根据HIS医院编码查询对应的科室")
	@GetMapping("/getHisDept/hosCode")
	public APIResponse<PageInfo<NavDestHisEntity>> getHisDeptByHosCode(@RequestParam String hosCode,
                                                                 @RequestParam(required = false, defaultValue = "1") int pageNo,
                                                                 @RequestParam(required = false, defaultValue = "10") int limit) {
		PageHelper.startPage(pageNo,limit);
		List<NavDestHisEntity> pageInfo = navDestHisSV
				.selectList(TK.select(NavDestHisEntity.class)
				.column("id","dept_code","dept_name")
				.where().andEqualTo(NavDestHisEntity::getHosCode,hosCode).end());
		return successPage(pageInfo);
	}

	@ApiOperation("云景医院查询")
	@GetMapping("/yunJin/hospital")
	public APIResponse<PageInfo<HospitalCodeMapEntity>> yunJinHospital(
			@RequestParam(required = false) String hosName,
			@RequestParam(required = false, defaultValue = "1") int pageNo,
			@RequestParam(required = false, defaultValue = "10") int limit
	) {
		PageHelper.startPage(pageNo,limit);
		List<HospitalCodeMapEntity> hospitalCodeMapPageInfo = hospitalCodeMapSV
				.selectList(TK.selectWhere(HospitalCodeMapEntity.class)
				.andEqualTo(HospitalCodeMapEntity::getHospitalName,hosName).end());
		return successPage(hospitalCodeMapPageInfo);
	}

	@ApiOperation("云景医院科室查询")
	@GetMapping("/yunJin/dept")
	public APIResponse<PageInfo<NavDestYjEntity>> yunJinDept(
			@RequestParam(required = false) String hosCode,
			@RequestParam(required = false) String deptType,
			@RequestParam(required = false, defaultValue = "1") int pageNo,
			@RequestParam(required = false, defaultValue = "10") int limit
	) {
		PageHelper.startPage(pageNo,limit);
		List<NavDestYjEntity> hospitalCodeMapPageInfo = navDestYjSV
				.selectList(TK.selectWhere(NavDestYjEntity.class)
				.andEqualTo(NavDestYjEntity::getBdgId,hosCode)
						.andEqualTo(NavDestYjEntity::getDeptType,deptType).end());
			
		return successPage(hospitalCodeMapPageInfo);
	}


}
